#' @TODO 利用clusterProfiler进行KEGG GO超几何富集分析
#' @title ## 利用clusterProfiler进行KEGG GO超几何富集分析
#' @param geneList 利用R包clusterProfiler进行富集分析时所有基因列表
#' @param geneAndlogFC *data.frame*
#' 只为绘制KEGG和弦图准备
#' 基因名所在列名 需要为`gene`，log2FC所在列名需要为`log2FC`,
#' 如果为NULL则不绘制KEGG和弦图，GO与KEGG全部使用clusterProfiler包进行分析
#' @param output_dir 文件输出目录,需要以/结尾
#' @param saveplot 是否会生成本地图片文件与富集总结果
#' @param var_name 用来命名文件夹以及结果
#'
#' @Author *WYK*
#'
GO_KEGG <- function(
    geneList = NULL, saveplot = F, output_dir = "./", var_name = NULL, geneAndlogFC = NULL,
    adj_m = "BH", p_cut = .05,
    width_single = 5, height_single = 4.5, width_circ = 10) {
  if (is.null(var_name)) {
    var_name <- deparse(substitute(deg_res))
  }

  library(tidyverse)
  library(cowplot)
  library(clusterProfiler)
  library(DOSE)
  library(org.Hs.eg.db)
  library(enrichplot)

  # print(keytypes(org.Hs.eg.db))

  id <- bitr(
    geneID = geneList,
    fromType = "SYMBOL",
    toType = "ENTREZID",
    OrgDb = "org.Hs.eg.db"
  )

  KEGG_res <- enrichKEGG(
    gene = id$ENTREZID,
    organism = "hsa",
    pvalueCutoff = p_cut,
    pAdjustMethod = adj_m,
    use_internal_data = F,
    qvalueCutoff = .5
  )
  KEGG_res <- setReadable(KEGG_res, OrgDb = org.Hs.eg.db, keyType = "ENTREZID")

  KEGG_bar_plot <- barplot(KEGG_res,
    title = "KEGG",
    showCategory = 10
  ) +
    theme(plot.margin = unit(c(0.2, 0.2, 0.2, 0.2), "cm"))
  KEGG_dot_plot <- dotplot(KEGG_res,
    title = "KEGG",
    showCategory = 10
  ) +
    theme(plot.margin = unit(c(0.2, 0.2, 0.2, 0.2), "cm"))

  if (nrow(as.data.frame(KEGG_res)) == 0) {
    cli::cli_alert_info(cli::style_bold("KEGG没有富集结果"))
    KEGG_bar_plot <- KEGG_dot_plot <- ggplot()
  }


  GO_MF <- enrichGO(
    gene = id$ENTREZID,
    OrgDb = "org.Hs.eg.db",
    keyType = "ENTREZID",
    ont = "MF", # One of "BP", "MF", and "CC" subontologies, or "ALL" for all three.
    pvalueCutoff = p_cut,
    pAdjustMethod = adj_m,
    qvalueCutoff = .5,
    readable = TRUE
  )
  GO_MF <- setReadable(GO_MF, OrgDb = org.Hs.eg.db, keyType = "ENTREZID")
  # GO_MF@result %>% data.table::fwrite(., sprintf("%s_GO_MF_res.txt", var_name), sep = "\t")
  GO_MF_bar <- barplot(GO_MF,
    title = "Molecular Function",
    showCategory = 10
  ) +
    theme(plot.margin = unit(c(0.2, 0.2, 0.2, 0.2), "cm"))
  GO_MF_dot <- dotplot(GO_MF,
    title = "Molecular Function",
    showCategory = 10
  ) +
    theme(plot.margin = unit(c(0.2, 0.2, 0.2, 0.2), "cm"))

  if (nrow(as.data.frame(GO_MF)) == 0) {
    cli::cli_alert_info(cli::style_bold("GO MF没有富集结果"))
    GO_MF_bar <- GO_MF_dot <- ggplot()
  }

  GO_BP <- enrichGO(
    gene = id$ENTREZID,
    OrgDb = "org.Hs.eg.db",
    keyType = "ENTREZID",
    ont = "BP", # One of "BP", "BP", and "CC" subontologies, or "ALL" for all three.
    pvalueCutoff = p_cut,
    pAdjustMethod = adj_m,
    qvalueCutoff = .5,
    readable = TRUE
  )
  GO_BP <- setReadable(GO_BP, OrgDb = org.Hs.eg.db, keyType = "ENTREZID")
  # GO_BP@result %>% data.table::fwrite(., sprintf("%s_GO_BP_res.txt", var_name), sep = "\t")
  GO_BP_bar <- barplot(GO_BP,
    title = "Biological Process",
    showCategory = 10
  ) +
    theme(plot.margin = unit(c(0.2, 0.2, 0.2, 0.2), "cm"))
  GO_BP_dot <- dotplot(GO_BP,
    title = "Biological Process",
    showCategory = 10
  ) +
    theme(plot.margin = unit(c(0.2, 0.2, 0.2, 0.2), "cm"))

  if (nrow(as.data.frame(GO_BP)) == 0) {
    cli::cli_alert_info(cli::style_bold("GO BP没有富集结果"))
    GO_BP_bar <- GO_BP_dot <- ggplot()
  }


  GO_CC <- enrichGO(
    gene = id$ENTREZID,
    OrgDb = "org.Hs.eg.db",
    keyType = "ENTREZID",
    ont = "CC", # One of "BP", "CC", and "CC" subontologies, or "ALL" for all three.
    pvalueCutoff = p_cut,
    pAdjustMethod = adj_m,
    qvalueCutoff = .5,
    readable = TRUE
  )
  GO_CC <- setReadable(GO_CC, OrgDb = org.Hs.eg.db, keyType = "ENTREZID")
  # GO_CC@result %>% data.table::fwrite(., sprintf("%s_GO_CC_res.txt", var_name), sep = "\t")
  GO_CC_bar <- barplot(GO_CC,
    title = "Cellular Component",
    showCategory = 10
  ) +
    theme(plot.margin = unit(c(0.2, 0.2, 0.2, 0.2), "cm"))

  GO_CC_dot <- dotplot(GO_CC,
    title = "Cellular Component",
    showCategory = 10
  ) +
    theme(plot.margin = unit(c(0.2, 0.2, 0.2, 0.2), "cm"))

  if (nrow(as.data.frame(GO_CC)) == 0) {
    cli::cli_alert_info(cli::style_bold("GO CC没有富集结果"))
    GO_CC_bar <- GO_CC_dot <- ggplot()
  }

  GO_ALL <- enrichGO(
    gene = id$ENTREZID,
    OrgDb = "org.Hs.eg.db",
    keyType = "ENTREZID",
    ont = "ALL", # One of "BP", "CC", and "CC" subontologies, or "ALL" for all three.
    pvalueCutoff = p_cut,
    pAdjustMethod = adj_m,
    qvalueCutoff = .5,
    readable = TRUE
  )
  GO_ALL <- setReadable(GO_ALL, OrgDb = org.Hs.eg.db, keyType = "ENTREZID")

  GO_ALL_bar <- barplot(GO_ALL, split = "ONTOLOGY") + facet_grid(ONTOLOGY ~ ., scale = "free")
  GO_ALL_dot <- dotplot(GO_ALL, split = "ONTOLOGY") + facet_grid(ONTOLOGY ~ ., scale = "free")

  GO_ALL_list <- list(GO_ALL_bar = GO_ALL_bar, GO_ALL_dot = GO_ALL_dot)

  GOplotIn <- KEGG_res[1:6, c(1, 2, 6, 8)]
  GOplotIn$geneID <- str_replace_all(GOplotIn$geneID, "/", ",")
  colnames(GOplotIn) <- c("ID", "Term", "adj_pval", "Genes")
  GOplotIn$Category <- "KEGG"

  if (!is.null(geneAndlogFC)) {
    genedata <- data.frame(ID = geneAndlogFC$gene, logFC = geneAndlogFC$log2FC)

    library(GOplot)
    circ <- GOplot::circle_dat(GOplotIn, genedata)
    chord <- GOplot::chord_dat(data = circ, genes = genedata)

    KEGG_circ <- GOChord(
      data = chord,
      title = "",
      space = 0.01, # Term间距
      limit = c(1, 1),
      gene.order = "logFC",
      gene.space = 0.25,
      gene.size = 3.75,
      lfc.col = c("#367EB8", "white", "#E4191C"),
      ribbon.col = brewer.pal(length(GOplotIn$Term), "Paired"),
      process.label = 10
    )

    KEGG_circ$guides$size$title <- "Terms"

    KEGG_circ$guides$size$ncol <- 1

    KEGG_circ <- KEGG_circ + theme(
      legend.position = "right",
      legend.direction = "vertical",
      legend.box = "horizontal",
      legend.box.just = "top",
      legend.justification = "center"
    )
  }

  message("Analyzing is done, begin to save plot.")

  p_list_1 <- list(
    GO_BP_dot, GO_CC_dot, GO_MF_dot,
    GO_BP_bar, GO_CC_bar, GO_MF_bar,
    KEGG_bar_plot, KEGG_dot_plot
  )

  names(p_list_1) <- c(
    "GO_BP_dot", "GO_CC_dot", "GO_MF_dot",
    "GO_BP_bar", "GO_CC_bar", "GO_MF_bar",
    "KEGG_bar_plot", "KEGG_dot_plot"
  )

  GO_dot_h <- plot_grid(
    plotlist = list(GO_BP_dot, GO_CC_dot, GO_MF_dot),
    align = "h", nrow = 1, label_size = 20 # labels = "AUTO",
  )
  GO_bar_h <- plot_grid(
    plotlist = list(GO_BP_bar, GO_CC_bar, GO_MF_bar),
    align = "h", nrow = 1, label_size = 20 # labels = "AUTO",
  )

  GO_h <- list(GO_dot_h = GO_dot_h, GO_bar_h = GO_bar_h)

  ALL_bar_p <- plot_grid(
    plotlist = list(GO_BP_bar, GO_CC_bar, GO_MF_bar, KEGG_bar_plot),
    align = "h", nrow = 2, label_size = 20 # labels = "AUTO",
  )
  ALL_dot_p <- plot_grid(
    plotlist = list(GO_BP_dot, GO_CC_dot, GO_MF_dot, KEGG_dot_plot),
    align = "h", nrow = 2, label_size = 20 # labels = "AUTO",
  )

  ALL_p <- list(ALL_bar_p = ALL_bar_p, ALL_dot_p = ALL_dot_p)


  if (saveplot) {
    if (!dir.exists(sprintf("%sGO_KEGG_%s", output_dir, var_name))) {
      dir.create(sprintf("%sGO_KEGG_%s", output_dir, var_name), showWarnings = F, recursive = T)
    } else {
      message(sprintf("Dir '%sGO_KEGG_%s' is existed.", output_dir, var_name))
    }

    KEGG_res@result %>%
      data.table::fwrite(., sprintf("%sGO_KEGG_%s/table_KEGG_%s.txt", output_dir, var_name, var_name), sep = "\t")
    GO_BP@result %>%
      data.table::fwrite(., sprintf("%sGO_KEGG_%s/table_GO_BP_%s.txt", output_dir, var_name, var_name), sep = "\t")
    GO_MF@result %>%
      data.table::fwrite(., sprintf("%sGO_KEGG_%s/table_GO_MF_%s.txt", output_dir, var_name, var_name), sep = "\t")
    GO_CC@result %>%
      data.table::fwrite(., sprintf("%sGO_KEGG_%s/table_GO_CC_%s.txt", output_dir, var_name, var_name), sep = "\t")
    GO_ALL@result %>%
      data.table::fwrite(., sprintf("%sGO_KEGG_%s/table_GO_ALL_%s.txt", output_dir, var_name, var_name), sep = "\t")


    walk(as.list(1:length(p_list_1)), function(x) {
      ggsave(
        filename = sprintf("%sGO_KEGG_%s/figure_%s.pdf", output_dir, var_name, names(p_list_1)[x]), device = "pdf",
        plot = p_list_1[[x]], width = width_single, height = height_single
      )
    })

    walk(as.list(1:length(GO_ALL_list)), function(x) {
      ggsave(
        filename = sprintf("%sGO_KEGG_%s/figure_%s.pdf", output_dir, var_name, names(GO_ALL_list)[x]), device = "pdf",
        plot = GO_ALL_list[[x]], width = width_single * 1.5, height = height_single * 3
      )
    })

    walk(as.list(1:length(GO_h)), function(x) {
      ggsave(
        filename = sprintf("%sGO_KEGG_%s/figure_%s.pdf", output_dir, var_name, names(GO_h)[x]), device = "pdf",
        plot = GO_h[[x]], width = width_single * 3, height = height_single
      )
    })

    if (length(geneAndlogFC) != 0) {
      ggsave(
        filename = sprintf("%sGO_KEGG_%s/figure_KEGG_circ_%s.pdf", output_dir, var_name, var_name), device = "pdf",
        plot = KEGG_circ, width = width_circ, height = 5
      )
    }


    walk(as.list(1:length(ALL_p)), function(x) {
      ggsave(
        filename = sprintf("%sGO_KEGG_%s/figure_%s.pdf", output_dir, var_name, names(ALL_p)[x]), device = "pdf",
        plot = ALL_p[[x]], width = width_single * 2, height = height_single * 2
      )
    })
  }

  if (length(geneAndlogFC) != 0) {
    tmp <- list(
      KEGG_res, GO_BP, GO_CC, GO_MF, GO_ALL,
      KEGG_bar_plot, KEGG_dot_plot,
      GO_BP_dot, GO_BP_bar,
      GO_CC_dot, GO_CC_bar,
      GO_MF_dot, GO_MF_bar,
      GO_ALL_dot, GO_ALL_bar,
      KEGG_circ,
      GO_dot_h, GO_bar_h,
      ALL_bar_p, ALL_bar_p
    )

    names(tmp) <- c(
      "KEGG_res", "GO_BP", "GO_CC", "GO_MF", "GO_ALL",
      "KEGG_bar_plot", "KEGG_dot_plot",
      "GO_BP_dot", "GO_BP_bar",
      "GO_CC_dot", "GO_CC_bar",
      "GO_MF_dot", "GO_MF_bar",
      "GO_ALL_dot", "GO_ALL_bar",
      "KEGG_circ",
      "GO_dot_h", "GO_bar_h",
      "ALL_bar_p", "ALL_bar_p"
    )
  } else {
    tmp <- list(
      KEGG_res, GO_BP, GO_CC, GO_MF, GO_ALL,
      KEGG_bar_plot, KEGG_dot_plot,
      GO_BP_dot, GO_BP_bar,
      GO_CC_dot, GO_CC_bar,
      GO_MF_dot, GO_MF_bar,
      GO_ALL_dot, GO_ALL_bar,
      GO_dot_h, GO_bar_h,
      ALL_bar_p, ALL_bar_p
    )

    names(tmp) <- c(
      "KEGG_res", "GO_BP", "GO_CC", "GO_MF", "GO_ALL",
      "KEGG_bar_plot", "KEGG_dot_plot",
      "GO_BP_dot", "GO_BP_bar",
      "GO_CC_dot", "GO_CC_bar",
      "GO_MF_dot", "GO_MF_bar",
      "GO_ALL_dot", "GO_ALL_bar",
      "GO_dot_h", "GO_bar_h",
      "ALL_bar_p", "ALL_bar_p"
    )
  }

  return(tmp)
}




# 关于自定义基因集，用下面的函数进行分析

# 自定义基因集富集分析

# kegg_geneset3 <- clusterProfiler::read.gmt("c2.cp.kegg.v7.4.entrez.gmt")

# degs_gene$ENTREZID

# ekegg <- clusterProfiler::enricher(
#   gene  = degs_gene$ENTREZID,
#   keyType = "ncbi-geneid",
#   universe = kegg_geneset3$gene, #背景基因集
#   pvalueCutoff  = p_cut,
#   qvalueCutoff  = 0.2)

# x <- clusterProfiler::enricher(degs_gene$ENTREZID, TERM2GENE = kegg_geneset3,TERM2NAME = kegg_geneset3)

# x <- setReadable(x, OrgDb = org.Hs.eg.db, keyType = "ENTREZID")

# # x@result %>% View()

# x@result %>% write.table(x = .,file = './KEGG_enrich_res_all.txt',quote = F,sep = '\t',row.names = F)

# cowplot::ggsave(filename = './KEGG_enrich_res_all.pdf',
#                  plot = x_bar,width = 10,height = 8.95)
# cowplot::ggsave(filename = './KEGG_enrich_res_all.tiff',
#                  plot = x_bar,width = 10,height = 8.95,dpi = 300)
# cowplot::ggsave(filename = './KEGG_enrich_res_all_72.tiff',
#                  plot = x_bar,width = 10,height = 8.95,dpi = 72)

# cowplot::ggsave(filename = './KEGG_enrich_res_all-dot.pdf',
#                  plot = x_dot,width = 10,height = 8.95)
# cowplot::ggsave(filename = './KEGG_enrich_res_all-dot.tiff',
#                  plot = x_dot,width = 10,height = 8.95,dpi = 300)
# cowplot::ggsave(filename = './KEGG_enrich_res_all-dot_72.tiff',
#                  plot = x_dot,width = 10,height = 8.95,dpi = 72)



# gsea富集分析

######
#' @TODO gsea富集分析
#' @title ## gsea富集分析
#' @param deg_res 差异基因分析结果需要有gene log2FC做列名
#' @param return_file_style list
#' @param return_file 返回结果图片
#' @param output_dir 结果输出路径
#'
#' @Author *WYK*
######
GSEA_cluster <- function(deg_res = NULL, pvalueCutoff = 0.05, pAdjustMethod = "none", seed = 1110, saveplot = F, output_dir = NULL, var_name = NULL) {
  library(RColorBrewer)
  library(org.Hs.eg.db)
  library(clusterProfiler)
  library(cowplot)
  library(enrichplot)
  library(tidyverse)

  deg_all <- deg_res %>%
    arrange(desc(log2FC)) %>%
    dplyr::select(gene, log2FC)

  if (is.null(var_name)) {
    var_name <- paste0(sample(letters, 4), collapse = "")
  }

  gene_name <- bitr(deg_all$gene, fromType = "SYMBOL", toType = "ENTREZID", OrgDb = "org.Hs.eg.db", drop = F)

  tmp_data <- left_join(gene_name, deg_all %>% dplyr::rename(SYMBOL = gene))
  tmp_data <- na.omit(tmp_data)

  genelist <- tmp_data$log2FC
  names(genelist) <- tmp_data$ENTREZID

  gsea_kegg <- gseKEGG(
    geneList = genelist,
    verbose = T,
    seed = F,
    # nPerm = 1000,#
    keyType = "kegg", # 可以选择"kegg",'ncbi-geneid', 'ncib-proteinid' and 'uniprot'
    organism = "hsa", # 定义物种,
    pvalueCutoff = pvalueCutoff, # 自定义pvalue的范围
    pAdjustMethod = pAdjustMethod # 校正p值的方法
  )

  gsea_GOBP <- gseGO(
    geneList = genelist,
    ont = "BP",
    OrgDb = org.Hs.eg.db,
    keyType = "ENTREZID",
    pvalueCutoff = pvalueCutoff,
    pAdjustMethod = pAdjustMethod,
    verbose = TRUE,
    seed = F
  )

  gsea_GOCC <- gseGO(
    geneList = genelist,
    ont = "CC",
    OrgDb = org.Hs.eg.db,
    keyType = "ENTREZID",
    pvalueCutoff = pvalueCutoff,
    pAdjustMethod = pAdjustMethod,
    verbose = TRUE,
    seed = F
  )

  gsea_GOMF <- gseGO(
    geneList = genelist,
    ont = "MF",
    OrgDb = org.Hs.eg.db,
    keyType = "ENTREZID",
    pvalueCutoff = pvalueCutoff,
    pAdjustMethod = pAdjustMethod,
    verbose = TRUE,
    seed = F
  )

  gsea_kegg <- gsea_kegg %>%
    arrange(desc(enrichmentScore))

  p_gsea_kegg_line <- gseaplot2(
    x = gsea_kegg,
    geneSetID = gsea_kegg$ID[1:4], # 只显示前4个GSEA的结果
    title = "GESA KEGG", # 标题
    color = brewer.pal(8, "Set1"), # 颜色
    pvalue_table = FALSE,
    ES_geom = "line"
  ) # enrichment scored的展现方式 'line' or 'dot')

  p_gsea_kegg_dot <- gseaplot2(
    x = gsea_kegg,
    geneSetID = gsea_kegg$ID[1:4], # 只显示前4个GSEA的结果
    title = "GESA KEGG", # 标题
    color = brewer.pal(8, "Set1"), # 颜色
    pvalue_table = FALSE,
    ES_geom = "dot"
  ) # enrichment scored的展现方式 'line' or 'dot')


  gsea_GOBP <- gsea_GOBP %>%
    arrange(desc(enrichmentScore))

  p_gsea_GOBP_line <- gseaplot2(
    x = gsea_GOBP,
    geneSetID = gsea_GOBP$ID[1:4], # 只显示前4个GSEA的结果
    title = "GESA GO BP", # 标题
    color = brewer.pal(8, "Set1"), # 颜色
    pvalue_table = FALSE,
    ES_geom = "line"
  ) # enrichment scored的展现方式 'line' or 'dot')

  p_gsea_GOBP_dot <- gseaplot2(
    x = gsea_GOBP,
    geneSetID = gsea_GOBP$ID[1:4], # 只显示前4个GSEA的结果
    title = "GESA GO BP", # 标题
    color = brewer.pal(8, "Set1"), # 颜色
    pvalue_table = FALSE,
    ES_geom = "dot"
  ) # enrichment scored的展现方式 'line' or 'dot')


  gsea_GOCC <- gsea_GOCC %>%
    arrange(desc(enrichmentScore))

  p_gsea_GOCC_line <- gseaplot2(
    x = gsea_GOCC,
    geneSetID = gsea_GOCC$ID[1:4], # 只显示前4个GSEA的结果
    title = "GESA GO CC", # 标题
    color = brewer.pal(8, "Set1"), # 颜色
    pvalue_table = FALSE,
    ES_geom = "line"
  ) # enrichment scored的展现方式 'line' or 'dot')

  p_gsea_GOCC_dot <- gseaplot2(
    x = gsea_GOCC,
    geneSetID = gsea_GOCC$ID[1:4], # 只显示前4个GSEA的结果
    title = "GESA GO CC", # 标题
    color = brewer.pal(8, "Set1"), # 颜色
    pvalue_table = FALSE,
    ES_geom = "dot"
  ) # enrichment scored的展现方式 'line' or 'dot')


  gsea_GOMF <- gsea_GOMF %>%
    arrange(desc(enrichmentScore))

  p_gsea_GOMF_line <- gseaplot2(
    x = gsea_GOMF,
    geneSetID = gsea_GOMF$ID[1:4], # 只显示前4个GSEA的结果
    title = "GESA GO MF", # 标题
    color = brewer.pal(8, "Set1"), # 颜色
    pvalue_table = FALSE,
    ES_geom = "line"
  ) # enrichment scored的展现方式 'line' or 'dot')

  p_gsea_GOMF_dot <- gseaplot2(
    x = gsea_GOMF,
    geneSetID = gsea_GOMF$ID[1:4], # 只显示前4个GSEA的结果
    title = "GESA GO MF", # 标题
    color = brewer.pal(8, "Set1"), # 颜色
    pvalue_table = FALSE,
    ES_geom = "dot"
  ) # enrichment scored的展现方式 'line' or 'dot')


  gsea_line <- plot_grid(p_gsea_kegg_line, p_gsea_GOBP_line, p_gsea_GOCC_line, p_gsea_GOMF_line,
    nrow = 2
  )
  gsea_dot <- plot_grid(p_gsea_kegg_dot, p_gsea_GOBP_dot, p_gsea_GOCC_dot, p_gsea_GOMF_dot,
    nrow = 2
  )

  x <- list(
    p_gsea_kegg_line, p_gsea_GOBP_line, p_gsea_GOCC_line, p_gsea_GOMF_line,
    p_gsea_kegg_dot, p_gsea_GOBP_dot, p_gsea_GOCC_dot, p_gsea_GOMF_dot
  )

  names(x) <- c(
    "p_gsea_kegg_line", "p_gsea_GOBP_line", "p_gsea_GOCC_line", "p_gsea_GOMF_line",
    "p_gsea_kegg_dot", "p_gsea_GOBP_dot", "p_gsea_GOCC_dot", "p_gsea_GOMF_dot"
  )

  if (saveplot) {
    if (!dir.exists(sprintf("%s/GSEA_cluster_%s", output_dir, var_name))) {
      dir.create(sprintf("%s/GSEA_cluster_%s", output_dir, var_name), recursive = T)
    } else {
      message(sprintf("Dir '%s/GSEA_cluster_%s' is existed.", output_dir, var_name))
    }

    dir_now <- sprintf("%s/GSEA_cluster_%s/", output_dir, var_name)

    gsea_kegg@result %>% write_delim(
      x = ., file = sprintf("%sGSEA_KEGG_%s.txt", dir_now, var_name),
      delim = "\t", quote = "none"
    )
    gsea_GOBP@result %>% write_delim(
      x = ., file = sprintf("%sGSEA_GOBP_%s.txt", dir_now, var_name),
      delim = "\t", quote = "none"
    )
    gsea_GOCC@result %>% write_delim(
      x = ., file = sprintf("%sGSEA_GOCC_%s.txt", dir_now, var_name),
      delim = "\t", quote = "none"
    )
    gsea_GOMF@result %>% write_delim(
      x = ., file = sprintf("%sGSEA_GOMF_%s.txt", dir_now, var_name),
      delim = "\t", quote = "none"
    )

    for (i in 1:length(x)) {
      pdf(file = sprintf("%s%s.pdf", dir_now, names(x)[i]), width = 6, height = 4.8)
      print(x[[i]])
      dev.off()
    }

    ggsave(filename = sprintf("%sgsea_line_%s.pdf", dir_now, var_name), plot = gsea_line, width = 10, height = 8)
    ggsave(filename = sprintf("%sgsea_dot_%s.pdf", dir_now, var_name), plot = gsea_dot, width = 10, height = 8)
  }

  return(x)
}


# gesa 多分组举例
# GSEA_A <- GSEA_cluster(
#     deg_res = degs$A %>% as.data.frame(), pvalueCutoff = 0.05,
#     pAdjustMethod = "none", seed = 1110, saveplot = T, output_dir = output_dir, var_name = 'a_up'
# )
# GSEA_B <- GSEA_cluster(
#     deg_res = degs$B %>% as.data.frame(), pvalueCutoff = 0.05,
#     pAdjustMethod = "none", seed = 1110, saveplot = T, output_dir = output_dir, var_name ='b_up'
# )
# GSEA_C <- GSEA_cluster(
#     deg_res = degs$C %>% as.data.frame(), pvalueCutoff = 0.05,
#     pAdjustMethod = "none", seed = 1110, saveplot = T, output_dir = output_dir, var_name = 'c_up'
# )


# choosen_pathway <- data.table::fread("/Pub/Users/wangyk/project/tmp/mimandaB/gsea_pathway.txt") %>% as.data.frame()


# gsea_kegg_p <- map(c("GSEA_A", "GSEA_B", "GSEA_C"), function(x) {
#     y <- switch(x,
#         GSEA_A = "A",
#         GSEA_B = "B",
#         GSEA_C = "C"
#     )
#     z <- switch(x,
#         GSEA_A = "clusterA",
#         GSEA_B = "clusterB",
#         GSEA_C = "clusterC"
#     )

#     p_gsea_kegg_line <- gseaplot2(
#         x = get0(x)[["gsea_kegg"]] %>% filter(NES > 0),
#         geneSetID = get0(x)[["gsea_kegg"]] %>%
#         filter(NES > 0) %>%
#             filter(ID %in% {
#                 choosen_pathway %>%
#                     filter(cluster == y) %>%
#                     pull(ID)
#             }) %>% .$ID, # 只显示前4个GSEA的结果
#         title = z, # 标题
#         rel_heights = c(1.5, 0.45, .5),
#         color = brewer.pal(8, "Paired"), # 颜色
#         pvalue_table = FALSE,
#         ES_geom = "line"
#     ) +# enrichment scored的展现方式 'line' or 'dot')
#     theme(plot.margin = unit(c(.2,2.4,.1,.1),'cm'))

#     return(p_gsea_kegg_line)
# })
# gsea_kegg_p_all_NES_over_0 <- cowplot::plot_grid(plotlist = gsea_kegg_p, ncol = 3)


# gsea_kegg_p <- map(c("GSEA_A", "GSEA_B", "GSEA_C"), function(x) {
#     y <- switch(x,
#         GSEA_A = "A",
#         GSEA_B = "B",
#         GSEA_C = "C"
#     )
#     z <- switch(x,
#         GSEA_A = "clusterA",
#         GSEA_B = "clusterB",
#         GSEA_C = "clusterC"
#     )

#     p_gsea_kegg_line <- gseaplot2(
#         x = get0(x)[["gsea_kegg"]],
#         geneSetID = get0(x)[["gsea_kegg"]] %>%
#             filter(NES < 0) %>%
#             filter(ID %in% {
#                 choosen_pathway %>%
#                     filter(cluster == y) %>%
#                     pull(ID)
#             }) %>% .$ID, # 只显示前4个GSEA的结果
#         title = z, # 标题
#         rel_heights = c(1.5, 0.45, .5),
#         color = brewer.pal(8, "Paired"), # 颜色
#         pvalue_table = FALSE,
#         ES_geom = "line"
#     ) +# enrichment scored的展现方式 'line' or 'dot')
#     theme(plot.margin = unit(c(.2,2.4,.1,.1),'cm'))# enrichment scored的展现方式 'line' or 'dot')

#     return(p_gsea_kegg_line)
# })
# gsea_kegg_p_all_NES_down_0 <- cowplot::plot_grid(plotlist = gsea_kegg_p, ncol = 3)

# gsea_p <- cowplot::plot_grid(gsea_kegg_p_all_NES_over_0, gsea_kegg_p_all_NES_down_0, ncol = 1)
# plotout(od = "/Pub/Users/wangyk/project/tmp/mimandaB/gesa_kegg_choosen_pathway/", name = "gsea_kegg", w = 14, h = 9, p = gsea_p)


# gsea_kegg_p <- map(c("GSEA_A", "GSEA_B", "GSEA_C"), function(x) {
#     y <- switch(x,
#         GSEA_A = "A",
#         GSEA_B = "B",
#         GSEA_C = "C"
#     )
#     z <- switch(x,
#         GSEA_A = "clusterA",
#         GSEA_B = "clusterB",
#         GSEA_C = "clusterC"
#     )

#     p_gsea_kegg_line <- gseaplot2(
#         x = get0(x)[["gsea_kegg"]],
#         geneSetID = get0(x)[["gsea_kegg"]] %>%
#             filter(ID %in% {
#                 choosen_pathway %>%
#                     filter(cluster == y) %>%
#                     pull(ID)
#             }) %>% .$ID, # 只显示前4个GSEA的结果
#         title = z, # 标题
#         rel_heights = c(1.5, 0.45, .5),
#         color = brewer.pal(8, "Paired"), # 颜色
#         pvalue_table = FALSE,
#         ES_geom = "line"
#     ) # enrichment scored的展现方式 'line' or 'dot')

#     return(p_gsea_kegg_line)
# })
# gsea_kegg_p_all <- cowplot::plot_grid(plotlist = gsea_kegg_p, ncol = 3)

# plotout(od = "/Pub/Users/wangyk/project/tmp/mimandaB/gesa_kegg_choosen_pathway/", name = "gsea_kegg_3", w = 14, h = 5, p = gsea_kegg_p_all)


# degs$A
# #    gene      pvalue    FC adjusted_pvalue  log2FC
# #    <chr>      <dbl> <dbl>           <dbl>   <dbl>
# #  1 A1BG    1.31e- 2 0.899   0.0193        -0.154
# expr['A1BG',group_data %>% filter(group == 'A') %>% rownames(.)] %>% as.numeric() %>% mean
# # [1] 0.2334473
# expr['A1BG',group_data %>% filter(group != 'A') %>% rownames(.)] %>% as.numeric() %>% mean
# # [1] 0.2597099
# # 基因A1BG再A类亚型中下调，log2FC小于0，趋势相同。即，log2FC小于0代表在A中下调。




# KEGG富集示例--------

# gene_id <- clusterProfiler::bitr(
#     geneID = degs$degs %>% arrange(desc(log2FC)) %>% pull(gene),
#     fromType = "SYMBOL",
#     toType = "ENTREZID",
#     OrgDb = 'org.Hs.eg.db',
#     drop = T
# ) %>% rename(gene = 1)

# genelist <- data.frame(
#     "gene" = degs$degs %>% arrange(desc(log2FC)) %>% pull(gene),
#     "log2FC" = degs$degs %>% arrange(desc(log2FC)) %>% pull(log2FC)
# ) %>%
#     inner_join(gene_id) %>%
#     distinct() %>%
#     arrange(desc(log2FC))

# aa <- genelist$log2FC
# names(aa) <- genelist$ENTREZID

# gsea_res <- clusterProfiler::gseKEGG(
#   geneList = aa,
#   organism = "hsa",
#   keyType = "kegg",
#   exponent = 1,
#   minGSSize = 10,
#   maxGSSize = 500,
#   eps = 1e-20,
#   pvalueCutoff = 0.05,
#   pAdjustMethod = adj_m,
#   verbose = TRUE,
#   seed = 1234
# )

# ----------